package com.yitiao.ratelimit;

// 定义漏斗限流算法类
class FunnelRateLimiter {
    private long capacity; // 漏斗容量
    private double leakingRate; // 漏斗流速  每毫秒流出的容量
    private long leftQuota; // 剩余容量
    private long lastLeakingTime; // 上次漏水时间

    public FunnelRateLimiter(long capacity, double leakingRate) {
        this.capacity = capacity;
        this.leakingRate = leakingRate;
        this.leftQuota = capacity;
        this.lastLeakingTime = System.currentTimeMillis();
    }

    // 漏水操作
    private void makeSpace() {
        long now = System.currentTimeMillis();
        long delta = now - lastLeakingTime;
        long toLeak = (long) (delta * leakingRate);
        if (toLeak < 1) {
            return;
        }
        leftQuota += toLeak;
        if (leftQuota > capacity) {
            leftQuota = capacity;
        }
        lastLeakingTime = now;
    }

    // 尝试获取令牌
    public boolean tryAcquire(long quota) {
        makeSpace();
        if (leftQuota >= quota) {
            leftQuota -= quota;
            return true;
        }
        return false;
    }

    public long getLeftQuota(){
        return leftQuota;
    }
}
